package com.itheima.consultant.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class RedisUrlChecker {

    private final RedisTemplate<String, String> redisTemplate;
    private final ObjectMapper objectMapper;

    public RedisUrlChecker(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 检查Redis中embedding文件夹下是否存在特定URL
     * @param targetUrl 目标URL（如 "/E:/abc.pdf"）
     * @return 是否存在
     */
    public boolean checkUrlExists(String targetUrl) {
        // 构建SCAN命令的匹配模式（假设embedding文件夹下的键格式为 "embedding:*"）
        ScanOptions scanOptions = ScanOptions.scanOptions()
                .match("embedding:*")
                .count(100)  // 每次扫描100条，避免一次性加载过多
                .build();

        // 使用RedisTemplate的scan方法遍历键
        Iterator<String> keysIterator = redisTemplate.execute((RedisCallback<Iterator<String>>) connection -> {
            Cursor<byte[]> cursor = connection.scan(scanOptions);
            return new Iterator<String>() {
                @Override
                public boolean hasNext() {
                    return cursor.hasNext();
                }

                @Override
                public String next() {
                    return new String(cursor.next());
                }

                @Override
                public void remove() {
                    cursor.remove();
                }
            };
        });

        // 遍历所有匹配的键，检查JSON中的url字段
        while (keysIterator.hasNext()) {
            String key = keysIterator.next();
            String jsonValue = redisTemplate.opsForValue().get(key);

            if (jsonValue != null) {
                try {
                    // 将JSON字符串解析为Map
                    Map<String, Object> jsonMap = objectMapper.readValue(jsonValue, HashMap.class);

                    // 检查嵌套结构中的url字段（根据实际存储结构调整）
                    Map<String, Object> metadata = (Map<String, Object>) jsonMap.get("metadata");
                    if (metadata != null) {
                        String url = (String) metadata.get("url");
                        if (targetUrl.equals(url)) {
                            System.out.println("找到匹配的URL，键: " + key);
                            return true;
                        }
                    }
                } catch (Exception e) {
                    System.err.println("解析JSON失败，键: " + key + ", 错误: " + e.getMessage());
                }
            }
        }

        return false;
    }
}
